package com.itheima.wechat;

import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.itheima.service.OrderService;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Reference
    OrderService orderService;

    String APP_ID = "2016102100733815";
    String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCLo7OHf0m+GHQ76Y42+kF2CgrDSM9oqKboxlyCl3qKrwWafugU+OcNDbRXmsrO43Bd4SX3MLaT6Lc+YlQyr4/mrs3tCphTFi+k4CWkBRiWEfLT/VVji2xxb6F5jw+Vy3cbGH2h+ilJsjTLKX2usGeWOyTtnJ+GzGCHU8BY6pttIIRlKRHsdGCKS3DCK1OVNC92bRRifFHF+DQ66luJl8wRxWKiMlO0HFiv3AJpilVFTlEEZpftNYt+GpkfvAC5iYoLjYTN1AG/wtaQrBmU6NrzyV8raxEBCpVIz7GPy9IwiQJ0NNiv03lOlSnS1u5DL01gJxyi2y/Ura5Z8tEhWkr/AgMBAAECggEAUUIkwc+foQBn+0lRGcsNdtwnITbog1XJMyHjSZdOlw98akg5U6L4CU+VR3lrVXNiuy6+whbV2EKPB71+k7Q4QBwu9ya4N3lspjxNiyHwCbxOG3CLVQ8YPvaf97X5csjg+aKJ0U1a42jRcfwmCBbdYL3wI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F-8";
    String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwEposPS1KjaRXNGCazOlpBgxDRizNg0VFRi+rX/5UYM1oTR0jGM0YgTrEwadBBZbI/N4Cshr4/H3HiVNU6TwmnCPFl5ecZeSjeVKkPgbe7Ky2gqWQgmr5HJshdGHmKUm0WUW3egdNhb1Zp3IQC3/39SSlhawvP6ay34Z5Pc6rZOuzWk16ldUX9UBTrWmcvRvCaEVGlE/NYvKgn4qPAF5TtnEqRzvlkcwy3nx5K8UuDKeF+PHxQckqzkU+mJHZTFCgP3mVJIGTtN8f8z+jPQg15mSpqmBK0H5sE/AoX0Y3rw8vi1uAWnKJK/KLWKevrtraFpDiAY6vDCWTy6AcDhE0wIDAQAB";

    /**
     * 生成商户订单号（年月日时分秒 + 订单号）
     *
     * @param orderId
     * @return
     */
    private String outTradeNo(Integer orderId) {
        String dateStr = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        return dateStr + orderId;
    }

    /**
     * @param httpRequest
     * @param httpResponse
     * @param orderId      订单id
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/alipay")
    public void alipay(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Integer orderId) throws ServletException, IOException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                APP_ID,
                APP_PRIVATE_KEY,
                "json",
                CHARSET,
                ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
        //外网地址
        String net = "http://sqw2bi.natappfree.cc";

        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl(net + "/pages/orderSuccess.html?orderId=" + orderId);//支付成功之后你想调到哪里（可以跳回我们的系统）
        alipayRequest.setNotifyUrl(net + "/pay/alipayNotify.do");//支付宝会给我们用户支付的结果（我们一般在哪里吧订单修改为支付成功）

        //根据订单查询订单详情
        Map orderInfo = orderService.findById(orderId);
        //生成新的订单号
        String outTradeNo = outTradeNo(orderId);
        //需要把outTradeNo更新到当前订单里面
        orderService.updateOutTradeNo(orderId, outTradeNo);

        JSONObject bizJson = new JSONObject();
        bizJson.put("out_trade_no", outTradeNo);//支付单号
        bizJson.put("product_code", "QUICK_WAP_PAY");

        bizJson.put("total_amount", 1000);//要付多少钱单位是 元
        bizJson.put("subject", orderInfo.get("setmeal"));//支付内容，我们可以用套餐名称

        alipayRequest.setBizContent(bizJson.toJSONString());//填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    Logger log = LoggerFactory.getLogger(PayController.class);

    @RequestMapping("/wxpay")
    public void wxpay() {

    }

    @RequestMapping("/uninpay")
    public void uninpay() {

    }

    @RequestMapping("/jdpay")
    public void jdpay() {

    }


    /**
     * 支付宝通知我们支付状态，在这个接口里面可以修改订单支付的状态
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/alipayNotify")
    @ResponseBody
    public String alipayNotify(HttpServletRequest request, HttpServletRequest response) throws Exception {

        log.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2"); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if (signVerified) {//验证成功

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            log.debug("支付成功...out_trade_no：" + out_trade_no + ",trade_status:" + trade_status);
            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
                orderService.updateOrderStatus(out_trade_no);
            }
        } else {//验证失败
            log.info("支付, 验签失败...");
        }

        return "success";
    }


}
